const { think } = require('thinkjs');
const Base = require('./base.js');
const moment = require('moment/moment.js');
const { default: BigNumber } = require('bignumber.js');

module.exports = class extends Base {
  async accountPanelAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const incomeTotal =
      (await this.model('income_list')
        .where({
          status: 1,
          type: ['!=', 'yajin'],
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;
    const outputTotal =
      (await this.model('output_list')
        .where({
          status: 1,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;
    const bill_in =
      (await this.model('bill_list')
        .where({
          type: 1,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;

    const bill_in_no =
      (await this.model('bill_list')
        .where({
          type: 1,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money_no')) || 0;

    const bill_in_tax =
      (await this.model('bill_list')
        .where({
          type: 1,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('tax')) || 0;

    const bill_out =
      (await this.model('bill_list')
        .where({
          type: 2,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money')) || 0;

    const bill_out_no =
      (await this.model('bill_list')
        .where({
          type: 2,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('money_no')) || 0;
    const bill_out_tax =
      (await this.model('bill_list')
        .where({
          type: 2,
          account_id: this.post('id'),
          update_time: ['between', [start, end]],
        })
        .sum('tax')) || 0;
    // const z_in =
    //   (await this.model('bill_list')
    //     .where({ type: 1, account_id: this.post('id'), bill_type: 1 })
    //     .sum('money')) || 0;
    // const z_o =
    //   (await this.model('bill_list')
    //     .where({ type: 2, account_id: this.post('id'), bill_type: 1 })
    //     .sum('money')) || 0;
    // const p_in =
    //   (await this.model('bill_list')
    //     .where({ type: 1, account_id: this.post('id'), bill_type: 2 })
    //     .sum('money')) || 0;
    // const p_o =
    //   (await this.model('bill_list')
    //     .where({ type: 2, account_id: this.post('id'), bill_type: 2 })
    //     .sum('money')) || 0;
    return this.success({
      incomeTotal: incomeTotal,
      outputTotal: outputTotal,
      bill_in: bill_in,
      bill_out: bill_out,
      bill_in_no: bill_in_no,
      bill_out_no: bill_out_no,
      bill_in_tax: bill_in_tax,
      bill_out_tax: bill_out_tax,
    });
  }

  async accountLineAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const types = [
      {
        name: '收入',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
      {
        name: '支出',
        type: 'bar',
        startData: moment(dateFilter[0]),
      },
    ];

    const data = {
      data: [],
    };
    const xData = [];
    const num = end.diff(start, 'months');

    for (let i = 0; i < num; i++) {
      xData.push(start.add(1, 'months').format('YYYY-MM'));
    }

    data.xData = xData;

    for (const item of types) {
      const addData = {
        name: item.name,
        type: item.type,
        showSymbol: false,
        data: [],
        tooltip: {
          valueFormatter: function(value) {
            return value + ' °C';
          },
        },
      };

      for (let i = 0; i < num; i++) {
        if (item.name === '收入') {
          const totalIncome =
            (await this.model('income_list')
              .where({
                status: 1,
                account_id: this.post('id'),
                type: ['!=', 'yajin'],
                update_time: [
                  'between',
                  moment('2000-01-01').format('YYYY-MM-DD HH:MM'),
                  item.startData
                    .add(1, 'months')
                    .endOf('month')
                    .format('YYYY-MM-DD HH:MM'),
                ],
              })
              .sum('money')) || 0;

          addData.data.push(totalIncome);
        } else if (item.name === '支出') {
          const totalOutput =
            (await this.model('output_list')
              .where({
                status: 1,
                account_id: this.post('id'),
                update_time: [
                  'between',
                  moment('2000-01-01').format('YYYY-MM-DD HH:MM'),
                  item.startData
                    .add(1, 'months')
                    .endOf('month')
                    .format('YYYY-MM-DD HH:MM'),
                ],
              })
              .sum('money')) || 0;
          addData.data.push(totalOutput);
        }
      }
      data.data.push(addData);
    }
    return this.success(data);
  }

  async accountShouzhiAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const income = await this.model('income_list')
      .where({
        type: ['!=', 'yajin'],
        status: 1,
        account_id: this.post('id'),
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const output = await this.model('output_list')
      .where({
        status: 1,
        account_id: this.post('id'),
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const arr = [
      {
        name: '收入',
        value: income || 0,
      },
      {
        name: '支出',
        value: output || 0,
      },
    ];

    return this.success(arr);
  }

  async accountYajinAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const income = await this.model('bill_list')
      .where({
        type: 1,
        account_id: this.post('id'),
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const output = await this.model('bill_list')
      .where({
        type: 2,
        account_id: this.post('id'),
        update_time: ['between', [start, end]],
      })
      .sum('money');
    const arr = [
      {
        name: '发票收入',
        value: income || 0,
      },
      {
        name: '发票开出',
        value: output || 0,
      },
    ];
    return this.success(arr);
  }

  async accountCatgoryAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]).format('YYYY-MM-DD');
    const end = moment(dateFilter[1]).format('YYYY-MM-DD');

    const dict = [
      { label: '押金', value: 'yajin' },
      { label: '水电', value: 'shuidian' },
      { label: '租赁', value: 'fangzu' },
      { label: '增值收入', value: 'zengzhi' },
    ];
    const list = await this.model('income_list')
      .where({
        status: 1,
        account_id: this.post('id'),
        update_time: ['between', [start, end]],
      })
      .select();
    const arr = [];
    for (const item of list) {
      const typeName = dict.find((res) => {
        return res.value === item.type;
      });
      if (!typeName) {
        continue;
      }
      const has = arr.find((res) => {
        if (res.name === typeName.label) {
          res.value = BigNumber(res.value)
            .plus(BigNumber(item.money))
            .toFixed(2);
        }
        return res.name === typeName.label;
      });
      if (!has) {
        arr.push({
          name: typeName.label,
          value: item.money || 0,
        });
      }
    }
    return this.success(arr);
  }

  async accountOutputAction() {
    const dateFilter = this.post('t');

    const start = moment(dateFilter[0]);
    const end = moment(dateFilter[1]);

    const dict = [
      { label: '房租', value: 'fangzu', startData: moment(dateFilter[0]) },
      { label: '基础成本', value: 'base', startData: moment(dateFilter[0]) },
      { label: '员工支出', value: 'staff', startData: moment(dateFilter[0]) },
      { label: '提成', value: 'royalty', startData: moment(dateFilter[0]) },
      {
        label: '招商成本',
        value: 'bussiness',
        startData: moment(dateFilter[0]),
      },
      { label: '内部管理', value: 'team', startData: moment(dateFilter[0]) },
      { label: '经营管理', value: 'manage', startData: moment(dateFilter[0]) },
      { label: '水电支出', value: 'utility', startData: moment(dateFilter[0]) },
    ];

    const data = {
      data: [],
    };

    const xData = [];
    const num = end.diff(start, 'months');

    for (let i = 0; i < num; i++) {
      xData.push(start.add(1, 'months').format('YYYY-MM'));
    }

    data.xData = xData;

    for (const dictItem of dict) {
      const addData = {
        name: dictItem.label,
        type: 'bar',
        stack: 'total',
        // label: {
        //   show: true,
        // },
        // emphasis: {
        //   focus: 'series',
        // },
        barWidth: 25,
        data: [],
        // tooltip: {
        //   valueFormatter: function(value) {
        //     return value + ' °C';
        //   },
        // },
      };
      for (let i = 0; i < num; i++) {
        // xData.push(itemData.format('YYYY-MM'));

        const totalOutput =
          (await this.model('output_list')
            .where({
              status: 1,
              type: dictItem.value,
              account_id: this.post('id'),
              update_time: [
                'between',
                moment('2000-01-01').format('YYYY-MM-DD HH:MM'),
                dictItem.startData
                  .add(1, 'months')
                  .endOf('month')
                  .format('YYYY-MM-DD HH:MM'),
              ],
            })
            .sum('money')) || 0;
        addData.data.push(totalOutput);
      }
      data.data.push(addData);
    }
    return this.success(data);
  }
};
